﻿using Microsoft.EntityFrameworkCore;
using RestfulApiV1.Data;
using RestfulApiV1.Data.Entity;
using RestfulApiV1.Interface.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RestfulApiV1.Implement.Data
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly RestfulApiDbContext _db;

        public EfRespository(RestfulApiDbContext db)
        {
            _db = db;
        }

        private DbSet<T> _entity;

        protected DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = _db.Set<T>();
                }
                return _entity;
            }
        }


        public IQueryable<T> Table 
        {
            get
            {
                return Entity;
            }
        }

        public void Add(T entity)
        {
            //Entity.CreatedTime = DateTime.Now;
            //Entity.UpdatedTime = DateTime.Now;
            Entity.Add(entity);

            _db.SaveChanges();
        }

        public void Add(IEnumerable<T> entities)
        {
            //foreach (var entity in entities)
            //{
            //    Entity.CreatedTime = DateTime.Now;
            //    Entity.UpdatedTime = DateTime.Now;
            //}
            Entity.AddRange(entities);

            _db.SaveChanges();
        }

        public void Delete(T entity)
        {
            Entity.Remove(entity);

            _db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entities)
        {
            Entity.RemoveRange(entities);

            _db.SaveChanges();
        }

        public T GetById(int id)
        {
            return Entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Update(T entity)
        {
            //Entity.UpdatedTime = DateTime.Now;
            Entity.Update(entity);

            _db.SaveChanges();
        }

        public void Update(IEnumerable<T> entities)
        {
            //foreach (var entity in entities)
            //{
            //    Entity.UpdatedTime = DateTime.Now;
            //}
            Entity.UpdateRange(entities);

            _db.SaveChanges();
        }

        public void Add(List<ArticleStatus> lists)
        {
            
        }

    }
}
